﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Text;
using System.IO;
using System.Net;

public partial class feeds : System.Web.UI.Page
{
    public string s;
    protected string userName;

    protected void Page_Load(object sender, EventArgs e)
    {

        userName = User.Identity.Name;
        DatabaseSqlDataSource1.SelectParameters.Add(new Parameter("currUser", TypeCode.String, userName));
        Literal1.Text = "Select a Feed";
       
    }




    //The method to show Feeds, takes input of an rss url
    //The method to show Feeds, takes input of an rss url
    public string showFeed(String feed, String xsl)
    {
        XslCompiledTransform transform = new XslCompiledTransform();
        StringBuilder output = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.ConformanceLevel = ConformanceLevel.Auto;
        XmlWriter write = XmlWriter.Create(output, settings);
        transform.Load(Server.MapPath(xsl));
        transform.Transform(feed, write);
        return output.ToString();
    }

    public string allFeeds()
    {
     //Shows the feed on top of your list, unless you have no feeds, then directs you to find page
        if (GridView2.Rows.Count < 1)
            return "You have no feeds! Go to <a href='find.aspx'>find</a> to add some";
        else
        {
            ArrayList rssList = new ArrayList();
            for (int i = 0; i < GridView2.Rows.Count; i++)
            {
                rssList.Add(GridView2.Rows[i].Cells[1].Text);
            }
            StringBuilder output = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.ConformanceLevel = ConformanceLevel.Auto;
            settings.Indent = true;
            XmlWriter write = XmlWriter.Create(output,settings);
            write.WriteStartDocument();
            write.WriteStartElement("opml");
            write.WriteAttributeString("version", "2.0");
            write.WriteStartElement("head");
            write.WriteStartElement("title");
            write.WriteString(User.Identity.Name+"'s Feeds");
            write.WriteEndElement();
            write.WriteEndElement();
            write.WriteStartElement("body");
            foreach (string s in rssList)
            {
                write.WriteStartElement("outline");
                write.WriteAttributeString("text", "");
                write.WriteAttributeString("xmlUrl", s);
                write.WriteEndElement();
            }
            write.WriteEndElement();
            write.WriteEndElement();
            write.WriteEndDocument();
            write.Close();

            //Literal1.Text = output.ToString();

           
                
                
            HttpWebRequest request = WebRequest.Create("http://feedblendr.com/api/") as HttpWebRequest;
            request.ContentType = "text/xml;charset=\"utf-8\"";
            request.Accept = "text/xml";
            request.Method = "POST";
            byte[] buffer = System.Text.Encoding.GetEncoding(1252).GetBytes(output.ToString());
            request.ContentLength = buffer.Length;
            Stream postData = request.GetRequestStream();
            postData.Write(buffer, 0, buffer.Length);
            postData.Close();
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            Encoding enc = System.Text.Encoding.GetEncoding(1252);
            StreamReader streamReader = new StreamReader(response.GetResponseStream(),enc);
            string temp = streamReader.ReadToEnd();

            XmlReader read = XmlReader.Create(new MemoryStream(ASCIIEncoding.Default.GetBytes(temp)));
            XmlDocument doc = new XmlDocument();
            doc.Load(read);
            XmlElement root = doc.DocumentElement;
            NameTable nt = new NameTable();
            XmlNamespaceManager man = new XmlNamespaceManager(nt);
            man.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            man.AddNamespace("fv", "http://www.feedville.com/developers/docs/xmlns#");
            XmlNodeList list = doc.GetElementsByTagName("atom:link");
            //Literal1.Text = list.Item(2).ToString();

            string feedURL = list.Item(2).Attributes["href"].Value.ToString();

            return showFeed(feedURL, "transforms/blendAgg.xsl");
            
            //Literal1.Text = temp;
                   

            //Literal1.Text = showFeed(GridView2.Rows[0].Cells[1].Text);

        }



    }

    //Sets buttons to point to RSS feed in Col 2 which is hidden
    //Grabs title of RSS feed and sets button.text to this title
    protected void GridView2_OnRowDataBound(object o, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            
            LinkButton b = (LinkButton) e.Row.Cells[0].Controls[0];

            b.Text = e.Row.Cells[2].Text;

            e.Row.Cells[1].Visible = false;
            e.Row.Cells[2].Visible = false;
        }
    }

    //When the button is clicked the showFeed method is passed the rss feed
    protected void GridView2_RowCommand(object sender,
                         GridViewCommandEventArgs e)
    {
       if (e.CommandName == "View Feed")
        {
            // get the categoryID of the clicked row

            int index = Convert.ToInt32(e.CommandArgument);
            // Delete the record 

            GridViewRow row = GridView2.Rows[index];

            Literal1.Text = showFeed(Server.HtmlDecode(row.Cells[1].Text), "transforms/rssagg.xsl");
       }
    }
    protected void aggFeeds_Click(object sender, EventArgs e)
    {
        Literal1.Text = allFeeds();
        
    }

}
